//express 8000
const https = require('https');
const SQLHelper = require('./SQLHelper')
const {formatTime} = require('./util')
//雪花算法生成id
const snowflake = require('./snowflake');
const { title } = require('process');
const { url } = require('inspector');

module.exports = function(app){
  ///登录拦截中间件
  function loginRouter(req,res,next){
    let token = req.headers.token
    if(token){
      SQLHelper(`select * from session where id = ${token}`).then(ret => {
        if(ret.length){
          let session = ret[0]
          req.session = {
            userId:session.userId,
            userName:session.userName,
            
          }
          next()
        }else{
          res.status(406).send({errorMsg:'当前用户未登录'})
        }
      })
    }else{
      res.status(405).send({errorMsg:'缺少token，请先进行登录'})
    }
  }

  ///让初登录以外的所有小程序接口都需要进行先验证登录
  app.use('/wx',loginRouter)


  //微信登录
  app.get('/wxlogin', (req, res,next) => {
      console.log(req)
      let code = req.query.code
      let appid = 'wxdba67a21856c52dc'
      let secret = 'e9f3eb96b94d7b2618ad49d3692450e7'
      https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
          ret.on('data', (ret) => {
              ret = JSON.parse(ret.toString())
              let openid = ret.openid
              if(!openid){
                res.send({errorMsg: ret.errMsg || '获取openid错误'})
              }else{ 
                //查询用户是否已经注册
                let queryMember = `select * from member where openId = '${openid}'`
                SQLHelper(queryMember).then(membersRet => {
                  if(membersRet.length){//用户已存在
                    ///挂载到req
                    req.member = membersRet[0]
                    next()
                  }else{//用户不存在，使用openid注册用户
                      SQLHelper(`INSERT INTO member(openId) VALUES('${openid}')`).then(newMember => {
                        //注册成功返回新用户信息
                        SQLHelper(queryMember).then(newMember => {
                          ///挂载到req
                          req.member = membersRet[0]
                          next()
                        })
                      })
                  }
              })
          }
      });
    }).on('error', (e) => {
      console.error(e)
      res.send({errorMsg:'获取openid错误'})
    });
  },(req,res) => {
    let member = req.member
    let token = snowflake()
    //缓存到token到session表
    SQLHelper(`
    INSERT INTO session(id,userId,userName,inTime,platform)
    VALUES(${token},'${member._id}','${member.nickName}','${formatTime(new Date())}','wx')
    `).then(ret => {
        res.send({
          nickName:member.nickName,
          token,
          openId:member.openId,
          avatarUrl:member.avatarUrl,
          _id:member._id
        })
      })
  })

  //修改用户信息
  app.put('/wx/member',(req,res) => {
    let userInfo = req.body
    console.log(req,req.query)
    SQLHelper(`
    update member
    set nickName = '${userInfo.nickName}',avatarUrl= '${userInfo.avatarUrl}'
    where _id = ${req.session.userId}
    `).then(ret => {
      console.log(ret)
      res.send({})
    })
  })

  ///获取收获地址列表
  ///memberId 用户ID 必填
  app.get('/wx/address',(req,res) => {
    if(req.session.userId){
      SQLHelper(`
      select * from address where state = 1 and memberId = ${req.session.userId}
      `).then(ret => {
          res.send(ret)
        })
    }else{
      res.send({errorMsg:'请传入memberId'})
    }
  })

  ///获取收获地址详情
  ///addressId 地址_ID 必填
  app.get('/wx/address/detail',(req,res) => {
    if(req.query.addressId){
      SQLHelper(`
      select * from address where _id = ${req.query.addressId}
      `).then(ret => {
          res.send(ret.length ? ret[0] : {errorMsg:'未获取到地址详情'})
        })  
    }else{
      res.send({errorMsg:'请传入addressId'})
    }
  })

  ///新增收获地址
  ///memberId 用户ID 必填
  ///receiver 收货人 必填
  ///phone 手机号 必填
  ///city 省市区 必填
  ///area 详细地址 非必填
  app.post('/wx/address',(req,res) => {
    if(req.body.receiver && req.body.phone && req.body.city){
      SQLHelper(`
      INSERT INTO address(state,memberId,receiver,phone,city,area)
      VALUES(1,'${req.session.userId}','${req.body.receiver}','${req.body.phone}','${req.body.city}','${req.body.area || ''}')
      `).then(ret => {
          res.send(ret)
        })  
    }else{
      res.send({errorMsg:'传入参数错误'})
    }
  })

  ///修改收获地址
  ///addressId 地址_ID 必填
  ///receiver 收货人 非必填
  ///phone 手机号 非必填
  ///city 省市区 非必填
  ///area 详细地址 非必填
  app.put('/wx/address',(req,res) => {
    if(req.body.addressId){
      //let sql = 'UPDATE address set '
      let updateKey = ['receiver','phone','city','area']
      let updateValues = []
      for(let i = 0;i < updateKey.length;i++){
          let key = updateKey[i],value = req.body[key]
          if(value) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE address set ${updateValues.join(',')} WHERE _id = ${req.body.addressId}`).then(ret => {
          res.send(ret)
        })  
    }else{
      res.send({errorMsg:'传入参数错误'})
    }
  })

  //修改为默认地址
  //传入addressId 数据库中主码：_id 必填
  //传入memberId 用户_id 必填
  ///isDefault 是否默认 非必填
  app.put('/wx/address/default',(req,res) => {
    let addressId = req.body.addressId,memberId = req.session.userId,isDefault = req.body.isDefault == 1 ? 1 : 0
    if(addressId && memberId){
      if(isDefault == 1){//设置为默认地址  
        ///取消其他默认地址
        SQLHelper(`
        UPDATE address
        set isDefault = 0
        WHERE isDefault = 1 AND memberId = ${memberId}
        `).then(ret => {
            SQLHelper(`
            UPDATE address
            set isDefault = 1
            WHERE _id= ${addressId}
            `).then(ret => {
                res.send(ret)
              })  
          })  
        }else{ ///取消默认地址
            SQLHelper(`
            UPDATE address
            set isDefault = 0
            WHERE _id= ${addressId}
            `).then(ret => {
                res.send(ret)
              })  
        }
    }else{
      res.send({errorMsg:'传入参数错误'})
    }
  })

  ///删除地址 逻辑删除
  //传入addressId 数据库中主码：_id 必填
  app.delete('/wx/address',(req,res) => {
    let addressId = req.body.addressId
    if(addressId){ 
        SQLHelper(`
        UPDATE address
        set state = 0
        WHERE _id = ${addressId}
        `).then(ret => {
          res.send(ret) 
          })  
    }else{
      res.send({errorMsg:'传入参数错误'})
    }
  })

  
  ///获取轮播图
  ///img 图片
  app.get('/wx/index/banners',(req,res) => {
    SQLHelper(`
    select * from banners where state = 1
    `).then(ret => {
      res.send(ret)
    })
  })

  ///获取发布信息information
  app.post('/wx/information',(req,res) => {
    if(req.body.address && req.body.contact){
      SQLHelper(`
      INSERT INTO information(state,address,contact,type,message)
      VALUES('1','${req.body.address}','${req.body.contact}','${req.body.type}','${req.body.message}')
      `).then(ret => {
          res.send(ret)
        })  
    }else{
      res.send({errorMsg:'传入参数错误1'})
    }
  })


  //分页获取宠物列表
  //pageSize 每页大小 默认10
  //pageNum 当前页 默认1
  //type
  app.get('/wx/index/dog_detail', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let name = req.query.name
    let type = req.query.type
    let whereSql = 'from dog_detail where state = 1'
    //按类型查询
    if (type) whereSql += ` and type = '${type}'`
    ///按标题关键字搜索
    if (name) whereSql += ` and name like "%${name}%"`
    SQLHelper(`
    select count(*) as total ${whereSql};
    select * ${whereSql} 
    limit ${pageSize} offset ${offset}
    `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })

  //根据id获取宠物参数
  app.post('/wx/index/dog_detailById',(req,res) => {
    console.log(req.body);
    if(req.body.id) {
      SQLHelper(`
      select * from dog_detail where state = 1 and id = ${req.body.id}
      `).then(ret => {
        res.send(ret)
      })
    }
  })

  //分页获取食物列表
  //pageSize 每页大小 默认10
  //pageNum 当前页 默认1
  //type
  app.get('/wx/index/food', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let name = req.query.name
    let type = req.query.type
    let whereSql = 'from food where state = 1'
    //按类型查询
    if (type) whereSql += ` and type = '${type}'`
    ///按标题关键字搜索
    if (name) whereSql += ` and name like "%${name}%"`
    SQLHelper(`
    select count(*) as total ${whereSql};
    select * ${whereSql} 
    limit ${pageSize} offset ${offset}
    `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })

//根据id获取食物参数
app.post('/wx/index/foodById',(req,res) => {
  console.log(req.body);
  if(req.body.id) {
    SQLHelper(`
    select * from food where state = 1 and id = ${req.body.id}
    `).then(ret => {
      res.send(ret)
    })
  }
})

//分页获取玩具列表
  //pageSize 每页大小 默认10
  //pageNum 当前页 默认1
  //type
  app.get('/wx/index/toy', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let name = req.query.name
    let type = req.query.type
    let whereSql = 'from toy where state = 1'
    //按类型查询
    if (type) whereSql += ` and type = '${type}'`
    ///按标题关键字搜索
    if (name) whereSql += ` and name like "%${name}%"`
    SQLHelper(`
    select count(*) as total ${whereSql};
    select * ${whereSql} 
    limit ${pageSize} offset ${offset}
    `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })

  //根据id获取玩具参数
app.post('/wx/index/toyById',(req,res) => {
  console.log(req.body);
  if(req.body.id) {
    SQLHelper(`
    select * from toy where state = 1 and id = ${req.body.id}
    `).then(ret => {
      res.send(ret)
    })
  }
})
//分页获取药品列表
  //pageSize 每页大小 默认10
  //pageNum 当前页 默认1
  //type
  app.get('/wx/index/medicine', (req, res) => {
    let pageSize = req.query.pageSize || 6
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let name = req.query.name
    let type = req.query.type
    let whereSql = 'from medicine where state = 1'
    //按类型查询
    if (type) whereSql += ` and type = '${type}'`
    ///按标题关键字搜索
    if (name) whereSql += ` and name like "%${name}%"`
    SQLHelper(`
    select count(*) as total ${whereSql};
    select * ${whereSql} 
    limit ${pageSize} offset ${offset}
    `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })

  //根据id获取药品参数
app.post('/wx/index/medicineById',(req,res) => {
  console.log(req.body);
  if(req.body.id) {
    SQLHelper(`
    select * from medicine where state = 1 and id = ${req.body.id}
    `).then(ret => {
      res.send(ret)
    })
  }
})
  

  //分页获取视频列表
  //pageSize 每页大小 默认10
  //pageNum 当前页 默认1
  app.get('/wx/videoos', (req, res) => {
    let pageSize = req.query.pageSize || 3
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let name = req.query.name
    let whereSql = 'from videoos where state = 1'
    ///按标题关键字搜索
    if (name) whereSql += ` and name like "%${name}%"`
    SQLHelper(`
    select count(*) as total ${whereSql};
    select * ${whereSql} 
    limit ${pageSize} offset ${offset}
    `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })

  //添加到收藏夹
  //select 收藏
  //select 
  app.put('/wx/haveSave',(req,res) => {
    let _id = req.body._id
    if(_id){ 
        SQLHelper(`
        UPDATE videoos
        set status = 1
        WHERE _id = ${_id}
        `).then(ret => {
          res.send(ret) 
          })  
    }else{
      res.send({errorMsg:'传入参数错误'})
    }
  })

  ///获取视频
  ///url 视频地址
  //title 视频标题
  app.get('/wx/videoos',(req,res) => {
    SQLHelper(`
    select * from videoos where state = 1
    `).then(ret => {
      res.send(ret)
    })
  })

  ////我的收藏
  ///获取收藏列表
  app.get('/wx/collect',(req,res) => {
    SQLHelper(`
    select * from videoos where status = 1 
    `).then(ret => {
        res.send(ret)
      })
  })

  //删除收藏（有问题）
  app.delete('/wx/collect',(req,res) => {
    SQLHelper(`
        UPDATE videoos
        set status = 0
        WHERE id = ${collectData}
        `).then(ret => {
          res.send(ret) 
          })  
    })

    ///获取购物车信息
    app.get('/wx/shopping',(req,res) => {
      SQLHelper(`
      select * from dog_detail where state = 0
      `).then(ret => {
        res.send(ret)
      })
    })

    ///获取为你推荐信息
    app.get('/wx/recommand',(req,res) => {
      SQLHelper(`
      select * from recommand where state = 1
      `).then(ret => {
        res.send(ret)
      })
    })
    
    //根据id获取为你推荐网址
  app.post('/wx/recommand',(req,res) => {
    console.log(req.body);
    if(req.body.id) {
      SQLHelper(`
      select * from recommand where state = 1 and id = ${req.body.id}
      `).then(ret => {
        res.send(ret)
      })
    }
  })


    //获取购物车默认地址
    // app.get('/wx/shopping/address',(req,res) => {
    //   SQLHelper(`
    //   select * from address where isDefault = 1
    //   `).then(ret => {
    //     res.send(ret)
    //   })
    // })
    app.get('/wx/shopping/address',(req,res) => {
      if(req.session.userId){
        SQLHelper(`
        select * from address where isDefault and memberId = ${req.session.userId}
        `).then(ret => {
            res.send(ret)
          })
      }else{
        res.send({errorMsg:'请传入memberId'})
      }
    })

    ///加入会员
    app.post('/wx/vip',(req,res) => {
      if(req.body.name && req.body.phone && req.body.city){
        SQLHelper(`
        INSERT INTO vip(state,memberId,name,phone,city,sex,grade)
        VALUES(1,'${req.session.userId}','${req.body.name}','${req.body.phone}','${req.body.city}','${req.body.sex}','${req.body.grade}')
        `).then(ret => {
            res.send(ret)
          })  
      }else{
        res.send({errorMsg:'传入参数错误'})
      }
    })

    //获取会员信息
    app.get('/wx/vip/detail',(req,res) => {
      SQLHelper(`
      select * from vip where state = 1
      `).then(ret => {
        res.send(ret)
      })
    })

    //获取优惠券信息
    app.get('/wx/money/detail',(req,res) => {
      SQLHelper(`
      select * from money where state = 1
      `).then(ret => {
        res.send(ret)
      })
    })
    
    //已使用的优惠券
    // app.get('/wx/money1/detail',(req,res) => {
    //   console.log(req.body.openId)
    //   SQLHelper(`
    //   SELECT m.* FROM member_money mm
	  //     LEFT JOIN money m on mm.moneyId=m.id
    //   where mm.state=1 and m.state=1 and mm.openId=${req.body.openId}
    //   `).then(ret => {
    //     res.send(ret)
    //   })
    // })

}